package com.yto.hrreport.event.buttons {
	import com.as3xls.xls.ExcelFile;
	import com.as3xls.xls.Sheet;
	import com.yto.hrreport.command.ReportCommand;
	import com.yto.hrreport.event.buttons.superbutton.ButtonEvent;
	
	import flash.events.Event;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	
	import mx.collections.ArrayCollection;
	import mx.controls.DataGrid;
	import mx.controls.dataGridClasses.DataGridColumn;
	
	public class ExportButtonEvent extends ButtonEvent {
		
		private static var exportEvent : ExportButtonEvent = new ExportButtonEvent();
		
		private static var parentName : String;
		private var param : Object;
		private var fields : Array;
		
		public function ExportButtonEvent() {
			super();
		}
		
		public static function getInstance(parentName : String) : ExportButtonEvent {
			ExportButtonEvent.parentName = parentName;
			return exportEvent;
		}
		
		public function exportToExcel(event : Event) : void { 
			
			param = ReportCommand.getInstance(parentName).initParam("onBoExport");
			
			var sheet : Sheet = new Sheet(); 
			var dataProviderCollection:ArrayCollection = param.bodyGrid.dataProvider as ArrayCollection; 
			var rowCount:int = dataProviderCollection.length; 
			sheet.resize(rowCount + 1,param.bodyGrid.columnCount); 
			var columns:Array = param.bodyGrid.columns; 
			var i:int = 0; 
			
			fields = new Array();
			
			for each (var field:DataGridColumn in columns) { 
				fields.push(field.dataField.toString()); 
				sheet.setCell(0,i,field.headerText); 
				i++; 
			} 
			
			for(var r:int=0; r < rowCount; r++) { 
				var record:Object = dataProviderCollection.getItemAt(r); 
				insertRecordInSheet(r+1,sheet,record , param.bodyGrid); 
			} 
			
			var xls:ExcelFile = new ExcelFile(); 
			xls.sheets.addItem(sheet); 
			
			var bytes : ByteArray = xls.saveToByteArray(); 			
			
			var fr:FileReference = new FileReference(); 
			fr.save(bytes, param.parentCanvas.label + "_" + param.period + ".xls");   
		} 
		
		private function insertRecordInSheet(row:int,sheet:Sheet,record:Object , bodyGrid : DataGrid): void  { 
			var colCount:int = bodyGrid.columnCount;
			
			for(var c:int; c < colCount; c++) { 
				
				var i:int = 0; 
				
				for each(var field:String in fields){ 
					for each (var value:String in record){ 
						try {
							if(record[field] == null)
								continue;
							
							if (String(record[field]) == value) 
								sheet.setCell(row,i,value); 
							
						} catch(e : Error) {
							
						}
					} 
					
					i++; 
				} 
			}
			
			
		} 
		
	}
}